package com.bigdata.wsr.dataCheck.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 钉钉告警 工具类
 *
 * @author rui.wang
 * @date 2022/12/01
 */
public class DingDingUtil {
    private static OkHttpClient mClient;
    private static String url;

    //初始化客户端
    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10L, TimeUnit.SECONDS);
        builder.readTimeout(10L, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequestsPerHost(200);
        dispatcher.setMaxRequests(200);
        builder.dispatcher(dispatcher);
        mClient = builder.build();
        try {
            url = getSign();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用 POST 请求方法  依赖 OKhttp3
     *
     * @param message 所要发送的消息
     * @return 发送状态回执
     */
    public static String postWithJson(String message) {
//        String str = "{ \"at\": { \"isAtAll\": true }, \"text\": { \"content\": \" %s \"}, \"msgtype\":\"text\" }"; //这里@为全体成员
        String str = "{\"at\": {\"atMobiles\": [\"13855154686\"], \"isAtAll\": false}, \"text\": {\"content\": \" %s \"}, \"msgtype\": \"text\"}"; //具体@某个人【只需加上手机号即可】
        String format = String.format(str, message);
        JSONObject jsonObject = JSON.parseObject(format);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取签名
     *
     * @return 返回签名
     */
    private static String getSign() throws Exception {
        String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
        String token = "b57b7b4dd3f21ea9db318111cfc63bea27b016f999e30e3c2a224db62b46705d"; //钉钉官方所获取的token
        String secret = "SEC341a06b7009c23d194d1c4b03d3c8c63e1b028332e2ba580aca57373a8563982"; //前期准备中的加签
        long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return baseUrl + token + "&timestamp=" + timestamp + "&sign=" + URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }
}